<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>Base64IO</title>
    <style>
        .el-header, .el-footer {
            background-color: #B3C0D1;
            color: #333;
            text-align: center;
            line-height: 60px;
        }
        
        .el-main {
            background-color: #E9EEF3;
            color: #333;
            text-align: center;
            line-height: 60px;
        }
        
        body > .el-container {
            margin-bottom: 40px;
        }
    </style>
    <!-- vue2 -->
    <script src="script/vue_2.js"></script>
    <!-- element 引入样式 -->
    <link rel="stylesheet" href="css/element_ui_theme_chalk_2.15.8.css">
    <!-- element 引入组件库 -->
    <script src="script/element_ui_2.15.8.js"></script>
    <!-- jquery 3.6 -->
    <script src="script/jquery-3.6.0.min.js"></script>
	<script src="script/download.js"></script>
    <script type="module">
        
        var app = new Vue({
            el: '#app',
            data: { 
                outbase64: '',
                inbase64: '',
				infile: null,
				fileList: []
            },
			methods:{
				readfile:function(data) {
					var reader = new FileReader();
					reader.readAsDataURL(data.file);
					reader.onload = function (e) { 
						//部分文件会赋予不合适的mime类型，导致保存过程出错，例如：csv文件被解释成 application/vnd.ms-excel 而非 text/csv 。
						app.outbase64 = this.result; 
					}
				},
				savefile:function(){
					//正确的保存必须包含 data:mimetype;base64, 头。
					//在方法中即便显式给定了txt文件类型，但依然会根据字符串中的类型信息保存。
					download(this.inbase64, "sample.txt", "text/plain");
				}
			}
        })
    </script>
</head>
<body>
    <div id="app">
		<el-row :gutter="10">
			<el-col :span="12">
				<el-container>
					<el-header>Base64 to File</el-header>
					<el-main>
						<el-row :gutter="20">
							<el-input type="textarea" :rows="21" placeholder="请输入base64字符串" v-model="inbase64">
							</el-input>
						</el-row>
						<el-row :gutter="20">
							  <el-button style="margin-left: 10px;" size="small" type="success" @click="savefile">保存文件</el-button>
						</el-row>
					</el-main>
				</el-container>
			</el-col>
			<el-col :span="12">
				<el-container>
				<el-header>File to Base64</el-header>
					<el-main>
						<el-row :gutter="20">
							<el-upload
							  class="upload-demo"
							  action="#"
							  :http-request="readfile"
							  :file-list="fileList"
							  :show-file-list="false"> 
							  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
							</el-upload>
						</el-row>
						<el-row :gutter="20">
							<el-input type="textarea" :rows="21" placeholder="在此输出base64字符串" v-model="outbase64">
							</el-input>
						</el-row>
					</el-main>
				</el-container>
			</el-col>
		</el-row>
    </div>
</body>